﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 同步CRM物流发运单信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoCRMWayBillInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMStoCRMWayBillInfoController(ILogger<TMStoCRMWayBillInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            //_logger = loggerFactory.CreateLogger<TMStoCRMWayBillInfoController>();
        }

        /// <summary>
        /// 同步CRM物流发运单信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddCRMWayBillInfo([FromBody] TMStoCRMWayBillInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMStoCRMWayBillInfoResponseDto re = new TMStoCRMWayBillInfoResponseDto();
            CRM_AddLogisticsInfoResponseDto strRe = new CRM_AddLogisticsInfoResponseDto();
            CRM_AddLogisticsInfoRequestDto strRequest = new CRM_AddLogisticsInfoRequestDto();
            string waybill_no = strparm.waybill_no;
            string ddm_token_crm = "&token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY2NDg0NTIwNzk2MTciLCJ4ZGFwdXNlcmlkIjoiMTAwMzQwMTY3MDY0NjI5MDE4NjI0IiwieGRhcHRpbWVzdGFtcCI6IjA0MDhiZDhlY2VmZGM4NDg0MDkxOTBkOTM0NWUzMDBlOTFlZDQ3ZGQ1Y2ZhNTA0ODZhN2IzZWJmZjIzMTJhZjIzOWFlMjA5ZWJiZGI3OTNjZWYzZDE3ZWE1Y2RmYzJkMDAzNzhiYjUwYzM3NjdlMzE1NDI5YmIxNmNlMTgxYjUyYTZlYWM4MzE0Nzg3MDZlNTNkM2Q3NGY1OTlkZDVkNjdhYTdkNjY0MzQ1YjRhOWQwNTFmNzU3MTk3MjFlYWUwNjY3MGFlYzM1YzQ5NTczYTdmNDJhN2JiNTgwNTcifQ==&download=download&formId=67107c3d72a36d3165c8d3c5&uuid=0854437598cabccfe16c551e";
            int ydzt = 0;
            int zt = 0;
            try
            {

                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }           
                if (strMsg == "")
                {                   
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                    dic.Add("waybill_no", waybill_no);
                    DataTable gzwl_dt = MethodHelp.GetTableInfo("TMS0077", dic, con);//广州高景物流信息获取
                    if (gzwl_dt.Rows.Count > 0)
                    {
                        GZCRMAddLogisticsRequestDto data_input = new GZCRMAddLogisticsRequestDto();
                        List<GZCRMAddLogisticsDetails> details_input = new List<GZCRMAddLogisticsDetails>();
                        foreach (DataRow rows in gzwl_dt.Rows)
                        {
                            string qsdfj1 = "";
                            string qsdfj2 = "";
                            string qsdfj3 = "";
                            string is_signin = "";//签收状态
                            string y_sate = "";//运单状态
                            if (rows["receipt_adjunct"].ToString() != "")
                            {
                                var fj = JsonConvert.DeserializeObject<DDM_FJ_signin_adjunct[]>(rows["receipt_adjunct"].ToString());
                                if (fj != null)
                                {
                                    int i = 1;
                                    foreach (var row in fj)
                                    {
                                        if (i == 1)
                                        {
                                            qsdfj1 = row.url + ddm_token_crm;
                                        }
                                        if (i == 2)
                                        {
                                            qsdfj2 = row.url + ddm_token_crm;
                                        }
                                        if (i == 3)
                                        {
                                            qsdfj3 = row.url + ddm_token_crm;
                                        }
                                        i = i + 1;
                                    }
                                }
                            }

                            decimal qs_qty=0;
                            if (rows["receipt_adjunct"].ToString() == "")
                            {
                                y_sate = "车辆离厂";
                                is_signin = "未签收";

                            }
                            else
                            {
                                y_sate = "已签收";
                                is_signin = "已签收";
                                qs_qty = DB.ToDecimal(rows["ship_qty"].ToString());
                            }

                            data_input.ydh = rows["waybill_no"].ToString();
                            details_input.Add(new GZCRMAddLogisticsDetails
                            {
                                ydzbid = rows["id"].ToString(),
                                fhsqhid = rows["plan_no"].ToString(),
                                xsddhid = rows["saleorderline_no"].ToString(),
                                xsddh = rows["saleorder_no"].ToString(),
                                ddhh = rows["saleorderline_no"].ToString(),
                                shdh = rows["contacts_tel"].ToString(),
                                ckdh = rows["delivery_no"].ToString(),
                                khbh = rows["customer_code"].ToString(),
                                hth = rows["customerpo"].ToString(),
                                ssjd = "广州高景",
                                yjft = "",//运价分摊
                                qsrq = DB.ToDateTime(rows["receipt_date"].ToString()).ToString("yyyy-MM-dd"),
                                qsdfj1 = qsdfj1,
                                qsdfj2 = qsdfj2,
                                qsdfj3 = qsdfj3,
                                wlfy = "",//物流费用
                                qssl = qs_qty.ToString(),
                                fhsl = rows["ship_qty"].ToString(),
                                ddlx = "801_国内组件销售",
                                chrq = DB.ToDateTime(rows["shipping_date"].ToString()).ToString("yyyy-MM-dd"),
                                khmc = rows["customer_name"].ToString(),
                                qszt = is_signin,
                                qsdh = rows["delivery_no"].ToString(),
                                shr = rows["customer_contacts"].ToString(),
                                shdz = rows["delivery_address"].ToString(),
                                fhdz = rows["shipping_address"].ToString(),
                                pdatjsl = rows["ship_qty"].ToString(),
                                ddsl = rows["saleorder_qty"].ToString(),
                                yszt = y_sate,
                                sfyqs = is_signin,
                                khbm = rows["customer_code"].ToString(),
                                sj = rows["driver_name"].ToString(),
                                cph = rows["car_no"].ToString(),
                                wlbm = rows["material_code"].ToString(),
                                wlmc = rows["material_name"].ToString(),
                                wldw = ""
                            });
                        }
                        if (details_input.Count > 0)
                        {
                            data_input.mxb = details_input;
                        }
                        if (data_input != null)
                        {
                            urldic = new Dictionary<string, string>(); //URL获取dic
                            urldic.Add("function_description", "内部: 广州CRM物流状态更新");//查看URL配置表地址描述
                            DataTable url_dt2 = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                            if (url_dt2.Rows.Count > 0)
                            {
                                string jsonText = JsonConvert.SerializeObject(data_input);
                                var reAgv = DB.httpPost(url_dt2.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                WMS_CarInfoInPutResponseDto psp = JsonConvert.DeserializeObject<WMS_CarInfoInPutResponseDto>(reAgv);
                                if (psp.code > 0)
                                {
                                    strMsg = "WMS ERR:" + psp.message;
                                }
                            }
                        }

                    }
                    else
                    {
                        strMsg = "单号=<" + waybill_no + "> 找不到对应明细记录!";
                    }
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
